package com.android.tea.shopper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.tea.R;
import com.android.tea.TeaEncyclopediaApp;
import com.android.tea.adapter.ShoperAdapter;
import com.android.tea.api.ApiResult;
import com.android.tea.api.ApiReturnResultListener;
import com.android.tea.api.TeaApi;
import com.android.tea.entity.TeaCompany;
import com.android.tea.shopper.ShakeDetector.OnShakeListener;
import com.android.tea.util.TeaLog;

public class GoodShopperActivity extends Activity implements
		ChangeLayoutInterface, OnShakeListener {

	protected static final String tag = "GoodShopperActivity";
	private ListView listView;
	LinearLayout llLayout;
	Handler handler;

	public static GoodShopperActivity instance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		TeaEncyclopediaApp.list.add(this);

		instance = this;
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				TeaLog.e("MyHandler", "handleMessage......");
				super.handleMessage(msg);
			}
		};
		llLayout = new LinearLayout(ShopperActivity.instance);
		llLayout.setClickable(true);
		llLayout.setBackgroundResource(R.drawable.shock);
		llLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				TeaLog.e(tag, "点击画面,开始动画");
				StartSearch(null);
			}
		});
		setContentView(llLayout);
		// GetMyLocation();
		shakeDetector();
	}

	public void StartSearch(String locate) {
		shakeDetector.stop();
		String loaclString;
		if (locate == null) {
			double[] d = getLongitudeLatitude(ShopperActivity.instance);
			loaclString = d[0] + "," + d[1];
		} else {
			loaclString = locate;
		}
		String range = ShopperOptionsActivity.rangeStrings[getIntValue(ShopperOptionsActivity.RANGE_INT)];
		String teaClass = getStringValue(ShopperOptionsActivity.TEACLASS_KEY);
		String offer = ShopperOptionsActivity.averageStrings[getIntValue(ShopperOptionsActivity.AVERAGE_INT)];
		String toast = "坐标:" + loaclString + "\n范围:" + range + "\n茶系:"
				+ teaClass + " \n人均消费: " + offer;
		// Toast.makeText(ShopperActivity.instance, toast, Toast.LENGTH_LONG)
		// .show();

		TeaLog.e(tag, toast);

		llLayout.setClickable(false);

		showAmin(R.anim.shock1);
		TeaApi userApi;
		userApi = new TeaApi(this);
		userApi.setReturnResultListener(apiReturnResultListener);
		userApi.getTeaRecommends(1, loaclString, range, teaClass, offer);

	}

	LocationManager locationManager;

	public boolean GetMyLocation() {

		// 获取到LocationManager对象
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		// 根据设置的Criteria对象，获取最符合此标准的provider对象
		String currentProvider = locationManager.getProvider(
				LocationManager.GPS_PROVIDER).getName();

		// 根据当前provider对象获取最后一次位置信息
		Location currentLocation = locationManager
				.getLastKnownLocation(currentProvider);
		// 如果位置信息为null，则请求更新位置信息
		if (currentLocation == null) {
			locationManager.requestLocationUpdates(currentProvider, 1000, 0,
					locationListener);
		}

		return false;
	}

	public double[] getLongitudeLatitude(Context context) {
		double[] location = { 0.0D, 0.0D };

		try {
			LocationManager lm = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
			Location locationInfo = lm
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (locationInfo != null) {
				location[0] = locationInfo.getLongitude();
				location[1] = locationInfo.getLatitude();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return location;
	}

	private String getLocation() {
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// 获取经纬度
		if (locationManager != null) {
			long latestFixTime = Long.MIN_VALUE;
			Location bestLocation = null;
			List<String> allProviders = locationManager.getAllProviders();
			for (String provider : allProviders) {
				Location lastLocation = locationManager
						.getLastKnownLocation(provider);
				if (lastLocation != null) {
					long fixTime = lastLocation.getTime();
					if (fixTime > latestFixTime) {
						latestFixTime = fixTime;
						bestLocation = lastLocation;
					} else if (fixTime == latestFixTime) {
						float accuracy = lastLocation.getAccuracy();
						if (bestLocation != null
								&& bestLocation.getAccuracy() < accuracy) {
							bestLocation = lastLocation;
						}
					}

					return bestLocation.getLatitude() + ","
							+ bestLocation.getLongitude();
				}
			}

		}
		return "0,0";
	}

	@Override
	public void onBackPressed() {
		Activity parent = this.getParent();
		if (parent != null) {
			parent.onBackPressed();
		} else {
			super.onBackPressed();
		}
	}

	private GpsStatus gpsstatus;
	private GpsStatus.Listener gpsListener = new GpsStatus.Listener() {
		// GPS状态发生变化时触发
		@Override
		public void onGpsStatusChanged(int event) {
			// 获取当前状态
			gpsstatus = locationManager.getGpsStatus(null);
			switch (event) {
			// 第一次定位时的事件
			case GpsStatus.GPS_EVENT_FIRST_FIX:
				break;
			// 开始定位的事件
			case GpsStatus.GPS_EVENT_STARTED:
				break;
			// 发送GPS卫星状态事件
			case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
				Toast.makeText(ShopperActivity.instance,
						"GPS_EVENT_SATELLITE_STATUS", Toast.LENGTH_SHORT)
						.show();
				Iterable<GpsSatellite> allSatellites = gpsstatus
						.getSatellites();
				Iterator<GpsSatellite> it = allSatellites.iterator();
				int count = 0;
				while (it.hasNext()) {
					count++;
				}
				Toast.makeText(ShopperActivity.instance,
						"Satellite Count:" + count, Toast.LENGTH_SHORT).show();
				break;
			// 停止定位事件
			case GpsStatus.GPS_EVENT_STOPPED:
				Log.d("Location", "GPS_EVENT_STOPPED");
				break;
			}
		}
	};
	private LocationListener locationListener = new LocationListener() {
		// 位置发生改变时调用
		@Override
		public void onLocationChanged(Location location) {
			Log.d("Location", "onLocationChanged");
		}

		// provider失效时调用
		@Override
		public void onProviderDisabled(String provider) {
			Log.d("Location", "onProviderDisabled");
		}

		// provider启用时调用
		@Override
		public void onProviderEnabled(String provider) {
			Log.d("Location", "onProviderEnabled");
		}

		// 状态改变时调用
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d("Location", "onStatusChanged");
		}

	};
	ApiReturnResultListener apiReturnResultListener = new ApiReturnResultListener() {

		@Override
		public <T> void onReturnSucceedResult(int requestCode,
				ApiResult<T> apiResult) {
			TeaLog.e("aaaa", "onReturnSucceedResult");

			final ArrayList<TeaCompany> loadData = (ArrayList<TeaCompany>) apiResult
					.getList();

			try {
				llLayout.setBackgroundResource(R.anim.shock2);
				Object ob = llLayout.getBackground();
				final AnimationDrawable anim = (AnimationDrawable) ob;
				anim.stop();
				anim.start();
			} catch (OutOfMemoryError e) {

			}

			handler.postDelayed(new Runnable() {
				@Override
				public void run() {

					if (loadData.size() <= 0) {
						llLayout.setBackgroundResource(R.anim.shock1);
						Toast.makeText(ShopperActivity.instance, "没有找到合适的数据。",
								Toast.LENGTH_LONG).show();
						llLayout.setClickable(true);
					} else {
						setContentView(R.layout.allfriends);
						listView = (ListView) findViewById(R.id.listView1);
						ShoperAdapter adapter = new ShoperAdapter(
								ShopperActivity.instance, loadData);
						listView.setAdapter(adapter);
						llLayout.setClickable(true);
					}

					try {
						shakeDetector.start();
					} catch (Exception e) {
						e.printStackTrace();
						TeaLog.e("shakeDetector", "printStackTrace");
					}
					isSearchNow = false;

				}
			}, 700);

		}

		@Override
		public <T> void onReturnFailResult(int requestCode,
				ApiResult<T> apiResult) {
			Toast.makeText(ShopperActivity.instance, "查询失败，请稍后重试。 ",
					Toast.LENGTH_LONG).show();
			llLayout.setBackgroundResource(R.drawable.shock);
			setContentView(llLayout);
			llLayout.setClickable(true);
			try {
				shakeDetector.start();
			} catch (Exception e) {
				e.printStackTrace();
				TeaLog.e("shakeDetector", "printStackTrace");
			}
			isSearchNow = false;
		}
	};
	ShakeDetector shakeDetector = new ShakeDetector(ShopperActivity.instance);

	private void shakeDetector() {
		ShakeDetector shakeDetector = new ShakeDetector(
				ShopperActivity.instance);
		shakeDetector.registerOnShakeListener(this);
		try {
			shakeDetector.start();
		} catch (Exception e) {
			e.printStackTrace();
			TeaLog.e("shakeDetector", "printStackTrace");
		}

	}

	boolean isSearchNow = false;

	@Override
	public void onShake() {

		if (!shake) {
			return;
		}

		if (!isSearchNow) {
			TeaLog.e(tag, "检测到晃动, 开始动画");
			isSearchNow = true;
			StartSearch(null);
		}
	}

	private void showAmin(int aminId) {
		setContentView(llLayout);
		llLayout.setBackgroundResource(aminId);
		AnimationDrawable anim = null;
		Object ob = llLayout.getBackground();
		anim = (AnimationDrawable) ob;
		// anim.stop();
		anim.start();
	}

	@Override
	public void lookAt(TeaCompany sMember) {
		// setContentView(R.layout.good_shooper_details);
	}

	public void setStringValue(String key, String value) {
		SharedPreferences settings = getApplicationContext()
				.getSharedPreferences(ShopperOptionsActivity.SETTING, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(key, value);
		editor.commit();
	}

	public String getStringValue(String key) {
		SharedPreferences settings = getApplicationContext()
				.getSharedPreferences(ShopperOptionsActivity.SETTING, 0);
		String value = settings.getString(key, null);
		return value;
	}

	public boolean getBooleanValue(String key) {
		SharedPreferences settings = getSharedPreferences(
				ShopperOptionsActivity.SETTING, 0);
		boolean value = settings.getBoolean(key, true);
		return value;
	}

	public void setBooleanValue(String key, boolean value) {
		SharedPreferences settings = getSharedPreferences(
				ShopperOptionsActivity.SETTING, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean(key, value);
		editor.commit();
	}

	public int getIntValue(String key) {
		SharedPreferences settings = getSharedPreferences(
				ShopperOptionsActivity.SETTING, 0);
		int value = 0;

		try {
			value = settings.getInt(key, 0);
		} catch (Exception e) {
			try {
				String sValue = settings.getString(key, null);
				if (null != sValue)
					value = Integer.parseInt(sValue);
			} catch (Exception e1) {

			}
		}
		return value;
	}

	public void setIntValue(String key, int value) {
		SharedPreferences settings = getSharedPreferences(
				ShopperOptionsActivity.SETTING, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(key, value);
		editor.commit();
	}

	boolean shake = false;

	@Override
	protected void onPause() {
		Log.e("aaaaaaa", "-------------------");
		try {
			shake = false;
			// shakeDetector.stop();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		try {
			shake = true;
			// shakeDetector.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onResume();
	}

}
